<template>
	<view>
		<view class="number_value">
			<view class="number_value__number">
				<u-input type="text" :disabled="true" @click="click" :placeholder="placeholder" input-align="right"
					:value="input" :custom-style="{width: '360rpx',fontSize: '36rpx'}" maxlength="15" />
			</view>
			<view class="number_value__unit" v-show="showUnit">CNY</view>
		</view>

		<b-keyboard safe-area-inset-bottom @confirm="confirm" :confirmBtn="true" :number="input?input:placeholder" :cancelBtn="true"
			v-model="show" @change="change" @backspace="backspace" :mask="false" :tooltip="false" :eventId="eventId">
		</b-keyboard>
	</view>
</template>

<script>
	export default {
		name: "b-number-input",
		props: {
			value: {
				type: Number | String,
				default: ''
			},
			showUnit: {
				type: Boolean,
				default: true
			}
		},
		created() {
			this.input = this.formatNum(this.value);
			this.placeholder = this.input;

			// 监听全计算器模式输入
			uni.$on(this.eventId, (res) => {
				this.input = res;
				this.show = false;
			})
		},
		data() {
			return {
				show: false,
				input: '',
				placeholder: '',
				eventId: 'confirmCalc_' + this.$u.guid(24, true, 62)
			};
		},
		watch:{
			show(newVal){
				if(newVal) return;
				
				if(!this.input){
					this.input = this.placeholder;
				}
				
				this.input = this.formatNum(this.input);

			},
			input(newVal){
				this.$emit('input', newVal)
			}
		},
		methods: {
			click() {
				this.show = true;
				if (this.input) {
					this.placeholder = this.input;
					this.input = '';
				}
			},
			formatNum(num) {
				num = num.toString();
				if (num.indexOf(".") < 0) {
					num += ".00"
				} else if (num.substr(num.lastIndexOf(".")).length < 3) {
					num += "0"
				}
				
				return num;
			},
			// 点击退格键
			backspace() {
				if (this.input.length) this.input = this.input.substr(0, this.input.length - 1);
			},
			// 键盘按键发生变化
			change(detail) {
				this.input += detail;
			},
			confirm(e) {
				// this.input = this.formatNum(this.input);
			}
		}
	}
</script>

<style lang="scss">
	.number_value {
		display: flex;
		flex-direction: row;
		align-items: center;

		.number_value__unit {
			background-color: $uni-text-color-disable;
			padding: 0 20rpx;
			margin-left: 20rpx;
			height: 25;
			line-height: 25px;
			border-radius: 10px;
			font-weight: bold;
			color: $uni-text-color-placeholder;
		}
	}
</style>
